package common.service;

import common.model.WebUser;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;

/**
 *
 * @author shousuke
 */
public class AccountActivation {

    public Long generateActivationCode(WebUser user) {
        /* Activation code is derived from id * createddate(minute) + createddate(sec)
        of the user that is to be activated. */
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(user.getCreatedDate());
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        return user.getId() * minute + second;
    }

    public boolean validateActivationCode(EntityManager em, String username, Long activationCode) {
        WebUser user = (WebUser) em.createQuery("WebUser.findByUsername").getSingleResult();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(user.getCreatedDate());
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        Long actualActivationCode = user.getId() * minute + second;
        return actualActivationCode.equals(activationCode);
    }
}
